//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System.IO;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Security.Permissions;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Application;
using System;
using DotNetNuke.Entities.Portals;
using System.Web;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using DotNetNuke.Entities.Users;
using System.Collections;
using System.Collections.Generic;
using DotNetNuke.Common.Utilities;
using System.Text;
using DotNetNuke.Services.Localization;
using System.Web.UI.WebControls;
using DotNetNuke.Services.Personalization;
namespace DotNetNuke.Framework
{
	partial class DefaultPage : DotNetNuke.Framework.CDefault, IClientAPICallbackEventHandler
	{
		public int PageScrollTop
		{
			get
			{
				int _PageScrollTop = Null.NullInteger;
				if (ScrollTop != null && !String.IsNullOrEmpty(ScrollTop.Value) && Regex.IsMatch(ScrollTop.Value, "^\\d+$"))
				{
					_PageScrollTop = Convert.ToInt32(ScrollTop.Value);
				}
				return _PageScrollTop;
			}
			set { ScrollTop.Value = value.ToString(); }
		}
		private void InitializePage()
		{
			TabController objTabs = new TabController();
			TabInfo objTab;
			if (!String.IsNullOrEmpty(Request.QueryString["tabname"]))
			{
				string strURL = "";
				objTab = objTabs.GetTabByName(Request.QueryString["TabName"], ((PortalSettings)HttpContext.Current.Items["PortalSettings"]).PortalId);
				if (objTab != null)
				{
					List<string> parameters = new List<string>();
					for (int intParam = 0; intParam <= Request.QueryString.Count - 1; intParam++)
					{
						switch (Request.QueryString.Keys[intParam].ToLower())
						{
							case "tabid":
							case "tabname":
								break;
							default:
								parameters.Add(
									Request.QueryString.Keys[intParam] + "=" + Request.QueryString[intParam]);
								break;
						}
					}
					Response.Redirect(Common.Globals.NavigateURL(objTab.TabID, Null.NullString, parameters.ToArray()), true);
				}
				else
				{
					throw new HttpException(404, "Not Found");
				}
			}
			if (Request.IsAuthenticated)
			{
				switch (Host.AuthenticatedCacheability)
				{
					case "0":
						Response.Cache.SetCacheability(HttpCacheability.NoCache);
						break;
					case "1":
						Response.Cache.SetCacheability(HttpCacheability.Private);
						break;
					case "2":
						Response.Cache.SetCacheability(HttpCacheability.Public);
						break;
					case "3":
						Response.Cache.SetCacheability(HttpCacheability.Server);
						break;
					case "4":
						Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
						break;
					case "5":
						Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
						break;
				}
			}
			if (Host.DisplayCopyright)
			{
				Comment += string.Concat(Environment.NewLine, "<!--**********************************************************************************-->", Environment.NewLine, "<!-- DotNetNuke - http://www.dotnetnuke.com                                          -->", Environment.NewLine, "<!-- Copyright (c) 2002-2010                                                          -->", Environment.NewLine, "<!-- by DotNetNuke Corporation                                                        -->", Environment.NewLine, "<!--**********************************************************************************-->",
				Environment.NewLine);
			}
			Page.Header.Controls.AddAt(0, new LiteralControl(Comment));
			if (PortalSettings.ActiveTab.PageHeadText != Null.NullString && !Common.Globals.IsAdminControl())
			{
				Page.Header.Controls.Add(new LiteralControl(PortalSettings.ActiveTab.PageHeadText));
			}
			string strTitle = PortalSettings.PortalName;
			foreach (TabInfo tab in PortalSettings.ActiveTab.BreadCrumbs)
			{
				strTitle += string.Concat(" > ", tab.TabName);
			}
			if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.Title))
			{
				strTitle = PortalSettings.ActiveTab.Title;
			}
			Title = strTitle;
			if (this.FindControl("Body") != null)
			{
				if (!string.IsNullOrEmpty(PortalSettings.BackgroundFile))
				{
					((HtmlGenericControl)this.FindControl("Body")).Attributes["style"] = string.Concat("background-image:url(", PortalSettings.HomeDirectory + PortalSettings.BackgroundFile, ");");
				}
			}
			if (PortalSettings.ActiveTab.RefreshInterval > 0 && Request.QueryString["ctl"] == null)
			{
				MetaRefresh.Content = PortalSettings.ActiveTab.RefreshInterval.ToString();
			}
			else
			{
				MetaRefresh.Visible = false;
			}
			if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.Description))
			{
				Description = PortalSettings.ActiveTab.Description;
			}
			else
			{
				Description = PortalSettings.Description;
			}
			if (!string.IsNullOrEmpty(PortalSettings.ActiveTab.KeyWords))
			{
				KeyWords = PortalSettings.ActiveTab.KeyWords;
			}
			else
			{
				KeyWords = PortalSettings.KeyWords;
			}
			if (Host.DisplayCopyright)
			{
				KeyWords += ",DotNetNuke,DNN";
			}
			if (!string.IsNullOrEmpty(PortalSettings.FooterText))
			{
				Copyright = PortalSettings.FooterText;
			}
			else
			{
				Copyright = string.Concat("Copyright (c) ", DateTime.Now.Year, " by ", PortalSettings.PortalName);
			}
			if (Host.DisplayCopyright)
			{
				Generator = "DotNetNuke ";
			}
			else
			{
				Generator = "";
			}
			if (Request.QueryString["ctl"] != null && (Request.QueryString["ctl"] == "Login" || Request.QueryString["ctl"] == "Register"))
			{
				MetaRobots.Content = "NOINDEX, NOFOLLOW";
			}
			else
			{
				MetaRobots.Content = "INDEX, FOLLOW";
			}
			if (NonProductionVersion() && Host.DisplayBetaNotice)
			{
				string versionString = string.Format(" ({0} Version: {1})", DotNetNukeContext.Current.Application.Status, DotNetNukeContext.Current.Application.Version.ToString());
				Title += versionString;
			}
			if (PortalSettings.EnableSkinWidgets)
			{
				DotNetNuke.Framework.jQuery.RequestRegistration();
				ClientAPI.RegisterStartUpScript(Page, "initWidgets", string.Format("<script type=\"text/javascript\" src=\"{0}\" ></script>", ResolveUrl("~/Resources/Shared/scripts/initWidgets.js")));
			}
		}
		private void SetSkinDoctype(DotNetNuke.UI.Skins.Skin Skin)
		{
			string strLang = System.Globalization.CultureInfo.CurrentCulture.ToString();
			string strDocType = PortalSettings.ActiveTab.SkinDoctype;
			if (strDocType.Contains("XHTML 1.0"))
			{
				HtmlAttributes.Add("xml:lang", strLang);
				HtmlAttributes.Add("lang", strLang);
				HtmlAttributes.Add("xmlns", "http://www.w3.org/1999/xhtml");
			}
			else if (strDocType.Contains("XHTML 1.1"))
			{
				HtmlAttributes.Add("xml:lang", strLang);
				HtmlAttributes.Add("xmlns", "http://www.w3.org/1999/xhtml");
			}
			else
			{
				HtmlAttributes.Add("lang", strLang);
			}
			skinDocType.Text = PortalSettings.ActiveTab.SkinDoctype;
		}
		private void ManageRequest()
		{
			int AffiliateId = -1;
			if (Request.QueryString["AffiliateId"] != null)
			{
				if (Regex.IsMatch(Request.QueryString["AffiliateId"], "^\\d+$"))
				{
					AffiliateId = Int32.Parse(Request.QueryString["AffiliateId"]);
					Services.Vendors.AffiliateController objAffiliates = new Services.Vendors.AffiliateController();
					objAffiliates.UpdateAffiliateStats(AffiliateId, 1, 0);
					if (Request.Cookies["AffiliateId"] == null)
					{
						HttpCookie objCookie = new HttpCookie("AffiliateId");
						objCookie.Value = AffiliateId.ToString();
						objCookie.Expires = DateTime.Now.AddYears(1);
						Response.Cookies.Add(objCookie);
					}
				}
			}
			if (PortalSettings.SiteLogHistory != 0)
			{
				string URLReferrer = "";
				try
				{
					if (Request.UrlReferrer != null)
					{
						URLReferrer = Request.UrlReferrer.ToString();
					}
				}
				catch (Exception ex)
				{
				}
				string strSiteLogStorage = Host.SiteLogStorage;
				int intSiteLogBuffer = Host.SiteLogBuffer;
				Services.Log.SiteLog.SiteLogController objSiteLogs = new Services.Log.SiteLog.SiteLogController();
				UserInfo objUserInfo = UserController.GetCurrentUserInfo();
				objSiteLogs.AddSiteLog(PortalSettings.PortalId, objUserInfo.UserID, URLReferrer, Request.Url.ToString(), Request.UserAgent, Request.UserHostAddress, Request.UserHostName, PortalSettings.ActiveTab.TabID, AffiliateId, intSiteLogBuffer,
				strSiteLogStorage);
			}
		}
		private void ManageStyleSheets(bool PortalCSS, DotNetNuke.UI.Skins.Skin ctlSkin)
		{
			string ID;
			Hashtable objCSSCache = (Hashtable)DotNetNuke.UI.Utilities.DataCache.GetCache("CSS");
			if (objCSSCache == null)
			{
				objCSSCache = new Hashtable();
			}
			if (!PortalCSS)
			{
				ID = Common.Globals.CreateValidID(Common.Globals.HostPath);
				AddStyleSheet(ID, Common.Globals.HostPath + "default.css");
				ID = Common.Globals.CreateValidID(PortalSettings.ActiveTab.SkinPath);
				if (!objCSSCache.ContainsKey(ID))
				{
					if (File.Exists(Server.MapPath(ctlSkin.SkinPath) + "skin.css"))
					{
						objCSSCache[ID] = ctlSkin.SkinPath + "skin.css";
					}
					else
					{
						objCSSCache[ID] = "";
					}
					if (Host.PerformanceSetting != Common.Globals.PerformanceSettings.NoCaching)
					{
						DotNetNuke.UI.Utilities.DataCache.SetCache("CSS", objCSSCache);
					}
				}
				if (objCSSCache[ID] != null && !String.IsNullOrEmpty(objCSSCache[ID].ToString()))
				{
					AddStyleSheet(ID, objCSSCache[ID].ToString());
				}
				ID = Common.Globals.CreateValidID(ctlSkin.SkinSrc.Replace(".ascx", ".css"));
				if (objCSSCache.ContainsKey(ID) == false)
				{
					if (File.Exists(Server.MapPath(ctlSkin.SkinSrc.Replace(".ascx", ".css"))))
					{
						objCSSCache[ID] = ctlSkin.SkinSrc.Replace(".ascx", ".css");
					}
					else
					{
						objCSSCache[ID] = "";
					}
					if (Host.PerformanceSetting != Common.Globals.PerformanceSettings.NoCaching)
					{
						DotNetNuke.UI.Utilities.DataCache.SetCache("CSS", objCSSCache);
					}
				}
				if (objCSSCache[ID] != null && !String.IsNullOrEmpty(objCSSCache[ID].ToString()))
				{
					AddStyleSheet(ID, objCSSCache[ID].ToString());
				}
			}
			else
			{
				if (File.Exists(PortalSettings.HomeDirectoryMapPath + "portal.css"))
				{
					ID = Common.Globals.CreateValidID(PortalSettings.HomeDirectory);
					AddStyleSheet(ID, PortalSettings.HomeDirectory + "portal.css");
				}
			}
		}
		private void ManageFavicon()
		{
			string strFavicon = Convert.ToString(DotNetNuke.UI.Utilities.DataCache.GetCache("FAVICON" + PortalSettings.PortalId.ToString()));
			if (String.IsNullOrEmpty(strFavicon))
			{
				if (File.Exists(PortalSettings.HomeDirectoryMapPath + "favicon.ico"))
				{
					strFavicon = PortalSettings.HomeDirectory + "favicon.ico";
					if (Host.PerformanceSetting != Common.Globals.PerformanceSettings.NoCaching)
					{
						DotNetNuke.UI.Utilities.DataCache.SetCache("FAVICON" + PortalSettings.PortalId.ToString(), strFavicon);
					}
				}
			}
			if (!String.IsNullOrEmpty(strFavicon))
			{
				HtmlLink objLink = new HtmlLink();
				objLink.Attributes["rel"] = "SHORTCUT ICON";
				objLink.Attributes["href"] = strFavicon;
				Page.Header.Controls.Add(objLink);
			}
		}
		private Dictionary<string, string> ParsePageCallBackArgs(string strArg)
		{
			string[] aryVals = strArg.Split(new string[] { DotNetNuke.UI.Utilities.ClientAPI.COLUMN_DELIMITER }, StringSplitOptions.None);
			Dictionary<string, string> objDict = new Dictionary<string, string>();
			if (aryVals.Length > 0)
			{
				objDict.Add("type", aryVals[0]);
				switch ((DNNClientAPI.PageCallBackType)Enum.Parse(typeof(DNNClientAPI.PageCallBackType), objDict["type"]))
				{
					case DNNClientAPI.PageCallBackType.GetPersonalization:
						objDict.Add("namingcontainer", aryVals[1]);
						objDict.Add("key", aryVals[2]);
						break;
					case DNNClientAPI.PageCallBackType.SetPersonalization:
						objDict.Add("namingcontainer", aryVals[1]);
						objDict.Add("key", aryVals[2]);
						objDict.Add("value", aryVals[3]);
						break;
				}
			}
			return objDict;
		}

        private string RenderDefaultsWarning()
        {
            string warningLevel = Request.QueryString["runningDefault"].ToString();
            string warningMessage = string.Empty;
            switch (warningLevel)
            {
                case "1":
                    warningMessage = Services.Localization.Localization.GetString("InsecureAdmin.Text", Services.Localization.Localization.GlobalResourceFile);
                    break;
                case "2":
                    warningMessage = Services.Localization.Localization.GetString("InsecureHost.Text", Services.Localization.Localization.GlobalResourceFile);
                    break;
                case "3":
                    warningMessage = Services.Localization.Localization.GetString("InsecureDefaults.Text", Services.Localization.Localization.GlobalResourceFile);
                    break;
            }
            return warningMessage;
        }

		protected string HtmlAttributeList
		{
			get
			{
				if ((HtmlAttributes != null) && (HtmlAttributes.Count > 0))
				{
					StringBuilder attr = new StringBuilder("");
					foreach (string attributeName in HtmlAttributes.Keys)
					{
						if ((!String.IsNullOrEmpty(attributeName)) && (HtmlAttributes[attributeName] != null))
						{
							string attributeValue = HtmlAttributes[attributeName];
							if ((attributeValue.IndexOf(",") > 0))
							{
								string[] attributeValues = attributeValue.Split(',');
								for (int attributeCounter = 0; attributeCounter <= attributeValues.Length - 1; attributeCounter++)
								{
									attr.Append(" " + attributeName + "=\"" + attributeValues[attributeCounter] + "\"");
								}
							}
							else
							{
								attr.Append(" " + attributeName + "=\"" + attributeValue + "\"");
							}
						}
					}
					return attr.ToString();
				}
				else
				{
					return "";
				}
			}
		}

		protected override void OnUnload(EventArgs e)
		{
			base.OnUnload(e);
		}

		protected bool NonProductionVersion()
		{
			return DotNetNukeContext.Current.Application.Status != ReleaseMode.Stable;
		}

        public string RaiseClientAPICallbackEvent(string eventArgument)
        {
            Dictionary<string, string> objDict = ParsePageCallBackArgs(eventArgument);
            if (objDict.ContainsKey("type"))
            {
                if (DNNClientAPI.IsPersonalizationKeyRegistered(objDict["namingcontainer"] + ClientAPI.CUSTOM_COLUMN_DELIMITER + objDict["key"]) == false)
                {
                    throw new Exception(string.Format("This personalization key has not been enabled ({0}:{1}).  Make sure you enable it with DNNClientAPI.EnableClientPersonalization", objDict["namingcontainer"], objDict["key"]));
                }
                switch ((DNNClientAPI.PageCallBackType)Enum.Parse(typeof(DNNClientAPI.PageCallBackType), objDict["type"]))
                {
                    case DNNClientAPI.PageCallBackType.GetPersonalization:
                        return Personalization.GetProfile(objDict["namingcontainer"], objDict["key"]).ToString();
                    case DNNClientAPI.PageCallBackType.SetPersonalization:
                        Personalization.SetProfile(objDict["namingcontainer"], objDict["key"], objDict["value"]);
                        return objDict["value"];
                    default:
                        throw new Exception("Unknown Callback Type");
                }
            }
            return "";
        }

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			InitializePage();
			DotNetNuke.UI.Skins.Skin ctlSkin = DotNetNuke.UI.Skins.Skin.GetSkin(this);
			SetSkinDoctype(ctlSkin);
			if (PortalSettings.ActiveTab.DisableLink)
			{
				if (TabPermissionController.CanAdminPage())
				{
					string heading = Localization.GetString("PageDisabled.Header");
					string message = Localization.GetString("PageDisabled.Text");
					DotNetNuke.UI.Skins.Skin.AddPageMessage(ctlSkin, heading, message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				}
				else
				{
					if (PortalSettings.HomeTabId > 0)
					{
						Response.Redirect(Common.Globals.NavigateURL(PortalSettings.HomeTabId), true);
					}
					else
					{
						Response.Redirect(Common.Globals.GetPortalDomainName(PortalSettings.PortalAlias.HTTPAlias, Request, true), true);
					}
				}
			}
            //Manage canonical urls
            if (PortalSettings.PortalAliasMappingMode == PortalSettings.PortalAliasMapping.CanonicalUrl && PortalSettings.PortalAlias.HTTPAlias != PortalSettings.DefaultPortalAlias)
            {
                string originalurl = this.Context.Items["UrlRewrite:OriginalUrl"].ToString();

                //Add Canonical <link>
                HtmlLink canonicalLink = new HtmlLink();
                canonicalLink.Href = originalurl.Replace(PortalSettings.PortalAlias.HTTPAlias, PortalSettings.DefaultPortalAlias);

                canonicalLink.Attributes.Add("rel", "canonical");

                // Add the HtmlLink to the Head section of the page.
                Page.Header.Controls.Add(canonicalLink);
            }

			string messageText = "";
			if (Request.IsAuthenticated == true && string.IsNullOrEmpty(Request.QueryString["runningDefault"]) == false)
			{
				UserInfo userInfo = HttpContext.Current.Items["UserInfo"] as UserInfo;
				if ((userInfo.Username.ToLower() == "admin") || (userInfo.Username.ToLower() == "host"))
				{
					messageText = RenderDefaultsWarning();
					string messageTitle = Services.Localization.Localization.GetString("InsecureDefaults.Title", Services.Localization.Localization.GlobalResourceFile);
					UI.Skins.Skin.AddPageMessage(ctlSkin, messageTitle.ToString(), messageText.ToString(), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				}
			}
			ManageStyleSheets(false, ctlSkin);
			SkinPlaceHolder.Controls.Add(ctlSkin);
			ManageStyleSheets(true, ctlSkin);
			ManageFavicon();
			DotNetNuke.UI.Utilities.ClientAPI.HandleClientAPICallbackEvent(this);
            //add viewstateuserkey to protect against CSRF attacks
            if (User.Identity.IsAuthenticated)
            {
                ViewStateUserKey = User.Identity.Name;
            }

		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			if (!String.IsNullOrEmpty(ScrollTop.Value))
			{
				DotNetNuke.UI.Utilities.DNNClientAPI.AddBodyOnloadEventHandler(Page, "__dnn_setScrollTop();");
				ScrollTop.Value = ScrollTop.Value;
			}
		}
		protected override void OnPreRender(EventArgs evt)
		{
			base.OnPreRender(evt);


			if (!Common.Globals.IsAdminControl())
			{
				ManageRequest();
			}
			Page.Header.Title = Title;
			MetaGenerator.Content = Generator;
			MetaGenerator.Visible = (!String.IsNullOrEmpty(Generator));
			MetaAuthor.Content = PortalSettings.PortalName;
			MetaCopyright.Content = Copyright;
			MetaCopyright.Visible = (!String.IsNullOrEmpty(Copyright));
			MetaKeywords.Content = KeyWords;
			MetaKeywords.Visible = (!String.IsNullOrEmpty(KeyWords));
			MetaDescription.Content = Description;
			MetaDescription.Visible = (!String.IsNullOrEmpty(Description));
			if (jQuery.IsRequested)
				jQuery.RegisterScript(Page);
		}
	}
}
